<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跨域聊天室</title>
    <style>
      #messages {
        height: 70vh;
        overflow-y: auto;
        background-color: #eee;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div id="status">连接状态：</div>
      <button onclick="clearAll()">清理所有聊天内容</button>
      <div class="input-area">
        <input type="text" id="textInput" placeholder="输入文字消息..." />
        <form onsubmit="return false">
          <button onclick="sendText()">发送</button>
          <input
            type="file"
            id="fileInput"
            hidden
            accept="image/*, video/*, audio/*"
          />
          <button onclick="showFilePicker()">
            发送文件(图片、视频、音频文件)
          </button>
        </form>
      </div>
      <div id="messages"></div>
    </div>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.5/socket.io.min.js"
      crossorigin="anonymous"
    ></script>
    <script>
      console.log("111111111111111111-----------", Date.now());
      //   保证本地和服务端打开改index.html文件，连接socket和访问文件路径正常
      let serverport = "3000"; // nodejs后端启动的服务
      let ipport = location.hostname + ":" + serverport;
      console.log("ipport", ipport);
      const host = location.protocol + "//" + ipport;
      console.log("host", host);
      // 本地开发连接地址
      const socket = io("wss://" + ipport, {
        // transports: ["websocket"],

        transports: ["websocket"],
        // 优化重连策略
        reconnectionDelay: 3000,
        reconnectionAttempts: 3,
        // 心跳参数与服务端对齐
        pingTimeout: 60000,
        pingInterval: 5000,
      });

      socket.on("connect", () => {
        console.log("连接成功 ID:", socket.id);
        document.getElementById("status").innerHTML =
          "连接状态：" + "连接成功，" + "ID：" + socket.id;
      });

      socket.on("disconnect", (reason) => {
        console.error("[WebSocket] 连接断开 原因:", reason);
        sessionStorage.setItem("reason", JSON.stringify(reason));
      });

      socket.io.on("error", (err) => {
        console.error("[WebSocket] 全局错误:", err);
      });

      const fileInput = document.getElementById("fileInput");

      // 初始化消息显示
      socket.on("history", (msgs) => msgs.forEach(addMessage));
      socket.on("message", addMessage);

      // 文本消息发送
      function sendText(e) {
        const input = document.getElementById("textInput");
        const content = input.value.trim();
        if (content) {
          socket.emit("message", { type: "text", content });
          input.value = "";
        }
      }

      // 文件上传处理
      function showFilePicker() {
        fileInput.click();
      }

      fileInput.onchange = async function (e) {
        const file = e.target.files[0];
        if (!file) return;

        const formData = new FormData();
        formData.append("file", file);

        try {
          const res = await fetch(host + "/chatupload", {
            method: "POST",
            body: formData,
          });
          const { url, type } = await res.json();
          socket.emit("message", { type, content: url });
        } catch (err) {
          console.error("上传失败:", err);
        }
      };

      // 消息显示处理
      function addMessage(msg) {
        if(!msg.content) return
        console.log("addMessage", msg);
        const container = document.createElement("div");
        container.className = "message";

        let content = "";
        switch (msg.type) {
          case "text":
            content = `<div class="text">${msg.content}</div>`;
            break;
          case "image":
            content = `<img style="max-height: 200px;" src="${
              host + msg.content
            }">`;
            break;
          case "video":
            content = `<video  style="max-height: 200px;" controls src="${
              host + msg.content
            }"></video>`;
            break;
          case "audio":
            content = `<audio controls src="${host + msg.content}"></audio>`;
        }

        container.innerHTML = `
                ${content}
                <div class="time">${new Date(
                  msg.timestamp
                ).toLocaleString()}</div>
            `;
        document.getElementById("messages").appendChild(container);
        // window.scrollTo(0, document.body.scrollHeight);
      }

      document.addEventListener("DOMContentLoaded", () => {
        const form = document.querySelector("form");
        if (form) {
          form.addEventListener("submit", (e) => {
            e.preventDefault();
            console.log("表单提交已被拦截");
          });
        }
      });

      // 清空文件和消息
      const clearAll = async () => {
        try {
          const res = await fetch(host + "/chatclearall", {
            method: "get",
          });
        } catch (err) {
          console.error("上传失败:", err);
        }
      };

      window.addEventListener("beforeunload", () => {
        if (socket.connected) {
          socket.close(); // 显式关闭连接
          console.log("[客户端] 主动断开连接");
        }
      });
    </script>
  </body>
</html>
